import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Icon, Message, NumberPicker, Tab, Radio, Switch } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';
import BatchWeight from './BatchWeight';

const RadioGroup = Radio.Group;

export default function CcCompanyPrice({ price }) {
  const { ccPriceStore: store } = useStore();
  const [data, setData] = useState([]);
  const [active, setActive] = useState();
  const [modal, setModal] = useState({});
  const [priceInfo, setPriceInfo] = useState();
  const [enable, setEnable] = useState(true);
  const [priority, setPriority] = useState(null);
  // useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    const { startMainArea, startMinorAreas, endMainArea, endMinorAreas, priceType, portTypes } = price;
    (async () => {
      const res = await store.api.companyPrices({
        startMainArea,
        startMinorAreas,
        endMainArea,
        endMinorAreas,
        priceType,
        portTypes,
        includeCompanyIds: price.companyDiscounts.map((c) => c.companyId),
      });
      const { enable: priceEnable, priority: pricePriority } = price?.priceFactor || {};
      setEnable(priceEnable);
      setPriority(pricePriority);
      const companys = await store.getCompany();
      const resWithCompanyInfo = res.map((item) => {
        const companyInfo = companys.find((company) => company.id === item.companyId);
        if (companyInfo) {
          // 合并属性，你可以根据实际需求进行调整
          return {
            ...item,
            stopTakingOrders: companyInfo.stopTakingOrders,
          };
        }
        return item;
      });
      setActive(res[0]?.companyId);
      setData(resWithCompanyInfo);
      await init();
    })();
  }, [price]);

  async function init() {
    const res = await store.get(price?.id);
    setPriceInfo({ ...toJS(res) });
  }

  const handleSubmit = async () => {
    try {
      await store.update(priceInfo);
    } catch (_) {
      Message.error(t`修改失败`);
    }
  };

  const handleBatchSubmit = async (result) => {
    try {
      const { weight } = result;
      Dialog.confirm({
        title: t`确定修改吗?`,
        onOk: () => ensureEdit(active, { weight }),
      });
    } catch (error) {
      Message.error({ content: t`修改错误` });
    }
  };

  const ensureEdit = async (id, args) => {
    await store.batchSettingWeight(id, args);
    Message.success({ content: t`修改成功` });
    setModal({});
    await init();
  };

  const handleSwitch = (v) => {
    setEnable(v);
  };

  const handleSubmitPrice = async () => {
    const { id } = price;
    const params = {
      priceId: id,
      priceFactor: {
        enable,
        priority,
      },
    };
    Dialog.confirm({
      content: t`是否同步修改所有线路`,
      okProps: {
        children: '是',
      },
      cancelProps: {
        children: '否',
      },
      onOk: async () => {
        try {
          await store.updateFactor({ ...params, type: 1 });
          Message.success({ content: t`修改成功` });
        } catch (error) {
          Message.error({ content: t`修改失败`, duration: 7000 });
          throw error;
        }
      },
      onCancel: async () => {
        try {
          await store.updateFactor({ ...params, type: 0 });
          Message.success({ content: t`修改成功` });
        } catch (error) {
          Message.error({ content: t`修改失败`, duration: 7000 });
          throw error;
        }
      },
    });
  };

  return (
    <>
      <div style={{ marginLeft: 33 }}>
        <span style={{ fontSize: 15, fontWeight: 500 }}>{t`是否考虑价格因素?`}</span>
        <Switch style={{ marginLeft: 20, marginRight: 30 }} checked={enable} size="small" checkedChildren={t`是`} unCheckedChildren={t`否`} autoWidth onChange={handleSwitch} />
        {enable &&
          <RadioGroup
            value={priority}
            onChange={(v) => setPriority(v)}
            aria-labelledby="groupId"
          >
            <Radio id="apple" value={0}>
              {t`价格优先`}
            </Radio>
            <Radio id="watermelon" value={1}>
              {t`权重优先`}
            </Radio>
          </RadioGroup>}
        <Button type="primary" style={{ marginLeft: 30 }} onClick={handleSubmitPrice}>{t`提交修改`}</Button>
      </div>
      <Tab
        activeKey={active}
        onChange={(v) => setActive(v)}
      >
        {data.map((c) => {
          const { stopTakingOrders } = c;
          const cObj = priceInfo?.companyDiscounts.find((c0) => c0.companyId === c.companyId);
          return (
            <Tab.Item
              key={c?.companyId}
              title={
                <>
                  <span style={{ marginRight: 5 }}>
                    {`${c?.companyName}(${cObj?.weight})`}
                  </span>
                  {(stopTakingOrders && stopTakingOrders?.stopOrder) && <Icon className="iconfont icon-no-full" style={{ color: 'red' }} />}
                </>
              }
              excessMode="dropdown"
            >
              <PriceForm companyItem={cObj} stopTakingOrders={stopTakingOrders} onSubmit={handleSubmit} handleBatchSubmit={handleBatchSubmit} modal={modal} setModal={setModal} />
              <TauTable
                dataSource={c.priceConfigs}
                hidePagination
                columns={[
                  { title: t`序号`, dataIndex: 'idx', width: 44, cell: (_, idx) => idx + 1 },
                  { title: t`始发区域`, dataIndex: 'startMinorAreasText' },
                  { title: t`到达区域`, dataIndex: 'endMinorAreasText' },
                  { title: t`单程(RMB/HKD/MOP)`, width: 160, dataIndex: 'specificSingleFare', cell: (v) => v && `¥${v['RMB']}/$${v['HKD'] || 0}/$${v['MOP'] || 0}` },
                  { title: t`往返(RMB/HKD/MOP)`, width: 160, dataIndex: 'specificReturnFares', cell: (v) => v && `¥${v['RMB']}/$${v['HKD'] || 0}/$${v['MOP'] || 0}` },
                ]}
              />
            </Tab.Item>
          );
        })}
      </Tab>
    </>
  );
}

const PriceForm = observer(({ companyItem, stopTakingOrders, onSubmit, handleBatchSubmit, modal, setModal }) => {
  const [isPreview, setIsPreview] = useState(true);
  const [data, setData] = useState({ ...companyItem });

  const onClose = () => {
    setModal({ visible: false });
  };

  const handleEdit = (type) => {
    const { stopOrder } = stopTakingOrders || {};
    const commonProps = {
      content: t`当前公司已禁止接单, 是否继续操作?`,
      onOk: () => setIsPreview(false),
    };

    if (stopOrder) {
      return Dialog.confirm({
        ...commonProps,
        onOk: () => {
          if (type === 'batch') {
            setModal({ visible: 'open', onClose });
          } else {
            setIsPreview(false);
          }
        },
      });
    }

    if (type === 'batch') {
      setModal({ visible: 'open', onClose });
    } else {
      setIsPreview(false);
    }
  };


  return (
    <>
      <Form
        style={{ margin: 20 }}
        inline
        value={data}
        // defaultValue={companyItem}
        onChange={(values, item) => {
          const { name, value } = item;
          _.set(data, name, value);
          setData(data);
        }}
        isPreview={isPreview}
        colon
      >
        <Form.Item
          label={t`派单权重`}
          name="weight"
        >
          <NumberPicker defaultValue={companyItem?.weight} min={0} />
        </Form.Item>
        <Form.Item>
          {isPreview && <Button onClick={() => handleEdit('weight')}>{t`修改权重`}</Button>}
          {!isPreview &&
            <>
              <Form.Submit
                validate
                type="primary"
                onClick={(values) => {
                  setIsPreview(true);
                  _.assign(companyItem, values);
                  onSubmit?.(companyItem);
                }}
              >
                {t`保存`}
              </Form.Submit>
              <Form.Reset toDefault style={{ marginLeft: 8 }} onClick={() => setIsPreview(true)}>{t`取消`}</Form.Reset>
            </>
          }
        </Form.Item>
        <Button onClick={() => handleEdit('batch')}>{t`批量修改权重`}</Button>
      </Form>
      <BatchWeight modal={modal} onSubmit={handleBatchSubmit} />
    </>
  );
});
